package com.tools.controller.workflow;

import com.tools.pojo.analysis.dto.AnalysisRequest;
import com.tools.pojo.data.AnalysisResponseDTO;
import com.tools.pojo.data.MedicalAnalysisRequestDTO;
import com.tools.service.workflow.FlowEngineService;
import com.tools.utils.DTOConverter;
import com.tools.utils.ValidationResult;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


/**
 * 数据分析API控制器
 */
@Slf4j
@RestController
@RequestMapping("/data-analysis")
@RequiredArgsConstructor
public class DataAnalysisApiController {

    private final FlowEngineService flowEngineService;
    private final DTOConverter dtoConverter;

    /**
     * 接收前端JSON数据并执行数据分析流程
     */
    @PostMapping("/execute")
    public AnalysisResponseDTO  executeAnalysis(@RequestBody AnalysisRequest request) {
        try {
            log.info("接收到数据分析请求: {}", request.getBusinessKey());

            // 验证请求参数
            if (request.getData() == null || request.getData().getPatientDtos() == null ||
                    request.getData().getPatientDtos().isEmpty()) {
                return AnalysisResponseDTO.failure("JSON数据不能为空");
            }

            // 将JSON转换为DTO对象
            MedicalAnalysisRequestDTO medicalRequestDTO;
            try {
                medicalRequestDTO = request.getData();
            } catch (Exception e) {
                return AnalysisResponseDTO.failure("JSON数据格式错误: " + e.getMessage());
            }

            // 验证DTO对象
            ValidationResult validation = dtoConverter.validateMedicalAnalysisRequest(medicalRequestDTO);
            if (!validation.isValid()) {
                return AnalysisResponseDTO.failure(validation.getMessage());
            }

            // 生成业务键（如果未提供）
            String businessKey = generateBusinessKey(request, medicalRequestDTO);

            // 准备流程初始数据
            Map<String, Object> initialData = prepareInitialData(request, medicalRequestDTO, businessKey);

            // 启动并执行数据分析流程
            Long instanceId = flowEngineService.startFlow("DATA_ANALYSIS_FLOW", businessKey, initialData);
            flowEngineService.executeFlow(instanceId);

            // 构建成功响应
            return AnalysisResponseDTO.success(
                    instanceId,
                    businessKey,
                    request.getAnalysisType(),
                    "数据分析流程已启动"
            );

        } catch (Exception e) {
            log.error("数据分析流程执行失败", e);
            return AnalysisResponseDTO.failure("数据分析流程执行失败: " + e.getMessage());
        }
    }
    /**
     * 直接接收DTO对象（替代JSON字符串）
     */
    @PostMapping("/execute-dto")
    public AnalysisResponseDTO executeAnalysisWithDTO(
            @Valid @RequestBody MedicalAnalysisRequestDTO medicalRequestDTO,
            @RequestParam(required = false) String businessKey,
            @RequestParam(required = false) String analysisType) {

        try {
            log.info("接收到DTO数据分析请求，患者数: {}",
                    medicalRequestDTO.getPatientDtos() != null ? medicalRequestDTO.getPatientDtos().size() : 0);

            // 验证DTO对象
            ValidationResult validation = dtoConverter.validateMedicalAnalysisRequest(medicalRequestDTO);
            if (!validation.isValid()) {
                return AnalysisResponseDTO.failure(validation.getMessage());
            }

            // 生成业务键（如果未提供）
            if (businessKey == null || businessKey.trim().isEmpty()) {
                businessKey = "DTO_ANALYSIS_" + System.currentTimeMillis();
            }

            // 准备流程初始数据
            Map<String, Object> initialData = prepareInitialDataFromDTO(medicalRequestDTO, businessKey, analysisType);

            // 启动并执行数据分析流程
            Long instanceId = flowEngineService.startFlow("DATA_ANALYSIS_FLOW", businessKey, initialData);
            flowEngineService.executeFlow(instanceId);

            // 构建成功响应
            return AnalysisResponseDTO.success(
                    instanceId,
                    businessKey,
                    analysisType != null ? analysisType : "dto_analysis",
                    "DTO数据分析流程已启动"
            );

        } catch (Exception e) {
            log.error("DTO数据分析流程执行失败", e);
            return AnalysisResponseDTO.failure("DTO数据分析流程执行失败: " + e.getMessage());
        }
    }

    /**
     * 生成业务键
     */
    private String generateBusinessKey(AnalysisRequest request, MedicalAnalysisRequestDTO medicalRequestDTO) {
        if (request.getBusinessKey() != null && !request.getBusinessKey().trim().isEmpty()) {
            return request.getBusinessKey().trim();
        }

        // 基于DTO信息生成业务键
        return medicalRequestDTO.getSysCode() + "_" +
                medicalRequestDTO.getPatientDtos().size() + "PATIENTS_" +
                System.currentTimeMillis();
    }


    /**
     * 准备流程初始数据（从JSON请求）
     */
    private Map<String, Object> prepareInitialData(AnalysisRequest request,
                                                   MedicalAnalysisRequestDTO medicalRequestDTO,
                                                   String businessKey) {
        Map<String, Object> initialData = new HashMap<>();

        // 核心数据
        initialData.put("rawJsonData", request.getData());
        initialData.put("medicalRequestDTO", medicalRequestDTO);
        initialData.put("businessKey", businessKey);
        initialData.put("analysisType", request.getAnalysisType() != null ?
                request.getAnalysisType() : "default");

        // 元数据
        initialData.put("requestSource", "API_DTO");
        initialData.put("requestTime", System.currentTimeMillis());
        initialData.put("clientInfo", request.getClientInfo());

        // 配置参数
        if (request.getConfig() != null) {
            initialData.put("analysisConfig", request.getConfig());
        }

        return initialData;
    }

    /**
     * 准备初始数据（从DTO对象）
     */
    private Map<String, Object> prepareInitialDataFromDTO(MedicalAnalysisRequestDTO medicalRequestDTO,
                                                          String businessKey, String analysisType) {
        Map<String, Object> initialData = new HashMap<>();

        // 核心数据
        initialData.put("medicalRequestDTO", medicalRequestDTO);
        initialData.put("parsedData", dtoConverter.convertToMap(medicalRequestDTO));
        initialData.put("businessKey", businessKey);
        initialData.put("analysisType", analysisType != null ? analysisType : "dto_direct");

        // 元数据
        initialData.put("requestSource", "DTO_DIRECT");
        initialData.put("requestTime", System.currentTimeMillis());
        initialData.put("dataFormat", "DTO_OBJECT");

        return initialData;
    }

}
